<template>
  <view class="pickerMain">
    <view @click="open" v-if="props.showFormat && props.showFormat == 1" class="input" :style="textStyle" :class="{ 'bor': props.showBorder && props.showBorder == 1 }">
      {{ format }}
    </view>
    <!-- <uv-input placeholder="请输入内容" v-model="format" @focus="open" clearable></uv-input> -->
    <uv-picker ref="picker" :columns="props.columns" :keyName="props.keyName" @confirm="confirm"></uv-picker>
  </view>
</template>

<script setup lang="ts">
const instance = getCurrentInstance();
let props = defineProps([
  "modelValue",
  "placeholder",
  "columns",
  "keyName",
  "keyVal",
  "showBorder",
  "placeholderStyle",
  "showFormat",
]);
const emit = defineEmits(["update:modelValue"]);

let textStyle = computed(() => {
  let obj = {};
  if (props.placeholderStyle) {
    obj = { ...props.placeholderStyle };
  }
  if (props.modelValue) {
    obj["color"] = "#454648";
  }
  return obj;
});

let format = computed(() => {
  let text = props.placeholder ? props.placeholder : "请选择";
  let p = "";
  if (props.columns && props.columns.length) {
    let array = props.columns[0];
    for (let index = 0; index < array.length; index++) {
      const element = array[index];
      if (element[props.keyVal ? props.keyVal : "id"] == valueData.value) {
        p = element[props.keyName];
      } else if (element == valueData.value) {
        p = element;
      }
    }
  }
  return p ? p : text;
});

const valueData = computed({
  get() {
    return props.modelValue;
  },
  set(value: string) {
    console.log("value", value);
  },
});

let open = () => {
  instance.refs.picker.open();
};
let confirm = (e) => {
  if (props.keyVal) {
    emit("update:modelValue", e.value[0][props.keyVal]);
  } else if (e.value[0].hasOwnProperty("id")) {
    emit("update:modelValue", e.value[0]["id"]);
  } else {
    emit("update:modelValue", e.value[0]);
  }
};

defineExpose({ open });
</script>

<style lang="scss" scoped>
.pickerMain {
  width: 100%;
}

.input {
  color: #808080;
  display: inline-block;
  padding: 8px 0;
  border-radius: 2px;
  width: 100%;
}

.bor {
  border: 0.5px solid #dadbde;
  border-radius: 3px;
  padding-left: 10px;
}
</style>
